
#include "Timer.h"

#include "Common/Errors.h"

using namespace std;
using namespace ttg;
using namespace ttg::threads;
using namespace ttg::services;
using namespace ttg_internal::services;

//-------------
//--- Timer ---
//-------------

Timer *Timer::ref = NULL;

void Timer::startUnSafe(vector<Service *> &deps, const char *params)
{
	clock = new Clock();
	updater = new UpdaterThread();
}

void Timer::stopUnSafe()
{
	updater->terminate();
	SAFE_DELETE(updater);
	SAFE_DELETE(clock);
}

Timer::Timer()
	:Service("Timer", NULL, false)
{
	clock = NULL;
	updater = NULL;
	makeRegistration();
}

DWORD Timer::getTime()
{
	return (DWORD)(getMilliSeconds());
}

double Timer::getMilliSeconds()
{
#ifdef TTG_DEBUG
	if (clock == NULL)
		throw ttg::Error(Error::FATAL, "Timer", "getMilliSeconds",
						 "Timer wasn't started");
#endif
	return clock->getSeconds() * 1000.0;
}

math::uint64 Timer::setNotifier(
	    ttg::structures::Delegate<void, double> *loopback,
		double rate,
		bool is_continual,
		bool is_disabled)
{
	return updater->addEvent(new ttg_internal::services::TimeEvent(loopback,
																   rate,
																   getSeconds(),
																   is_continual,
																   !is_disabled));
}

double Timer::getSeconds()
{
#ifdef TTG_DEBUG
	if (clock == NULL)
		throw ttg::Error(Error::FATAL, "Timer", "getSeconds",
						 "Timer wasn't started");
#endif
	return clock->getSeconds();
}
